package com.btshop.file.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.btshop.file.util.FileUtil;
import com.btshop.file.util.OSSUtil;
import com.util.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: FileController
 * @description: 文件上传控制层
 * @author: 李东
 * @Date: 2020-7-16 14:41
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/file")
@Api(value = "文件服务接口", tags = "文件服务接口")
public class FileController {
    @Autowired
    private OSSUtil ossUtil;

    @ApiOperation(value = "文件上传接口", notes = "文件上传接口", response = Result.class)
    @ApiImplicitParams(@ApiImplicitParam(name = "file", value = "文件", dataType = "MultipartFile"))
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        // 方式一：上传字节数组
        log.info("FileController.upload param is {}", file);
        try {
            String filename = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            String uploadUrl = ossUtil.upload(bytes, filename);
            // 封装返回结果
            Map<String, String> resMap = new HashMap<>();
            resMap.put("uploadUrl", uploadUrl);
            log.info("FileController.upload return param is {}", resMap);
            return Result.buildSuccess("文件上传成功！", resMap);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        // 方式二：上传base64加密字符串
        // log.info("FileController.upload param is {}",file);
        // try {
        // String filename = file.getOriginalFilename();
        // byte[] bytes = file.getBytes();
        // String encode = new BASE64Encoder().encode(bytes);
        // String uploadUrl = ossUtil.upload(encode, filename);
        // // 封装返回结果
        // Map<String, String> resMap = new HashMap<>();
        // resMap.put("uploadUrl", uploadUrl);
        // log.info("FileController.upload return param is {}", resMap);
        // return Result.buildSuccess("文件上传成功！", resMap);
        // } catch (IOException e) {
        // e.printStackTrace();
        // throw new RuntimeException(e.getMessage());
        // }

        // 方式三：上传File
        // log.info("FileController.upload param is {}",file);
        // //MultipartFile 转换成临时文件
        // File newFile = FileUtil.MultipartFileToFile(file);
        // String uploadUrl = ossUtil.upload(newFile);
        // //删除临时文件
        // FileUtil.delete(file.getOriginalFilename());
        // //封装返回结果
        // Map<String,String> resMap = new HashMap<>();
        // resMap.put("uploadUrl",uploadUrl);
        // log.info("FileController.upload return param is {}",resMap);
        // return Result.buildSuccess("文件上传成功！",resMap);
    }


    /**
     * @description: 文件下载
     * @Param: [filrUrl]
     * @return: com.util.Result
     * @author: 李东
     * @time: 2020-7-17 9:10
     **/
    @ApiOperation(value = "文件下载接口", notes = "文件下载接口")
    @ApiImplicitParams(@ApiImplicitParam(name = "fileUrl", value = "文件url地址", dataType = "String"))
    @GetMapping("/download")
    public void download(@RequestParam("fileUrl") String fileUrl, HttpServletResponse response)
            throws IOException {
        byte[] bytes = FileUtil.getFileBytesByUrl(fileUrl);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);

        // 响应参数设置
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition",
                "attachment;filename=" + new String((fileName).getBytes("GBK"), "ISO8859-1"));
        response.addHeader("Content-Length", "" + bytes.length);
        OutputStream out = response.getOutputStream();
        response.setContentType("application/octet-stream");
        out.write(bytes);
        out.flush();
        out.close();
    }

    /**
     * @description: 查询所有文件信息接口
     * @return: com.util.Result
     * @author: 李东
     * @time: 2020-7-17 11:53
     **/
    @ApiOperation(value = "查询所有文件信息接口", notes = "查询所有文件信息接口")
    @PostMapping("/list")
    public Result fileList() {
        List<Map<String, String>> maps = ossUtil.listObjects();
        return Result.buildSuccess("查询所有文件成功！", maps);
    }


    /**
     * @description: 根据文件url删除文件
     * @Param: [fileUrl]
     * @return: com.util.Result
     * @author: 李东
     * @time: 2020-7-17 11:59
     **/
    @ApiOperation(value = "根据文件url删除文件", notes = "根据文件url删除文件")
    @ApiImplicitParams(@ApiImplicitParam(name = "fileUrl", value = "文件url地址", dataType = "String"))
    @GetMapping("/delete")
    public Result delete(@RequestParam("fileUrl") String fileUrl){
        ossUtil.deleteFile(fileUrl);
        return Result.buildSuccess("根据文件url删除文件成功！");
    }

}
